package com.xxxx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.xxxx.api.service.SSOService;
import com.xxxx.api.pojo.Admin;
import com.xxxx.api.utils.CookieUtil;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author : ymd
 * @Date : 2020/11/2 0002 16:15
 * @Version 1.0
 * @Description : 拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Reference(version = "1.0")
    private SSOService ssoService;
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    @Value("${user.ticket}")
    private String userTicket;

    //请求方法前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户信息
        String ticket = CookieUtil.getCookieValue(request, "ticket");
        if (!StringUtils.isEmpty(ticket)){
            Admin admin = ssoService.validate(ticket);
            request.getSession().setAttribute("user", admin);
            //重新设置失效时间
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            opsForValue.set(userTicket+":"+ticket, JSON.toJSONString(admin),30, TimeUnit.MINUTES);
            return true;
        }
        //验证失败，跳回登录
        response.sendRedirect(request.getContextPath()+"/login");
        return false;
    }
    //请求方法后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //处理方法后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
